﻿using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows;
using System.Windows.Input;

namespace NthDownload.Common.Interactivity.Behaviors
{
    /// <summary>
    /// Focuses the control that has been attached to on it's loaded event
    /// </summary>
    public class FocusOnLoad : Behavior<Control>
    {
        #region Override Methods

        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.Loaded -= ControlLoaded;
            AssociatedObject.Loaded += ControlLoaded;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            AssociatedObject.Loaded -= ControlLoaded;
        }

        #endregion Override Methods

        #region Event Handlers

        private void ControlLoaded(object sender, RoutedEventArgs e)
        {
            if (IsEnabled)
            {
                Keyboard.Focus(AssociatedObject);
            }
        }

        #endregion Event Handlers

        #region Dependancy Properties

        public bool IsEnabled
        {
            get { return (bool)GetValue(IsEnabledProperty); }
            set { SetValue(IsEnabledProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsEnabled.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsEnabledProperty =
            DependencyProperty.Register("IsEnabled", typeof(bool), typeof(FocusOnLoad), new PropertyMetadata(false));

        #endregion Dependancy Properties
    }
}
